package org.nfIt.annotation.aspect;

import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.nfIt.annotation.log.Log;
import org.nfIt.entity.system.SysOperLog;
import org.nfIt.service.AsyncOperLogService;
import org.nfIt.utils.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * ClossName:LogAspect
 * Pakage:org.nfIt.annotation.aspect
 * Description
 *
 * - @Aspect - 表示是个切面类
 *
 * @Author L
 * @Create 2024/9/11 19:39
 * @Version 2023.1.3
 */
@Aspect
@Component
@Slf4j
public class LogAspect {

    @Autowired
    private AsyncOperLogService operLogService;


    //环绕通知
    @Around(value = "@annotation(sysLog)")
    public Object doAroundAdvice(ProceedingJoinPoint joinPoint , Log sysLog) {
//        String title = sysLog.title();
//        log.info("LogAspect...doAroundAdvice方法执行了"+title);
//        System.out.println("LogAspect...doAroundAdvice方法执行了"+title);

        SysOperLog operLog = new SysOperLog();
        //业务调用之前封装数据
        LogUtil.beforeHandleLog(sysLog,joinPoint,operLog);

        Object proceed = null;
        try {
            // 执行业务方法，proceed - 业务方法返回值
            proceed = joinPoint.proceed();
//            System.out.println("在业务方法之后执行....");
            //业务方法之后,封装数据
            LogUtil.afterHandlLog(sysLog,proceed,operLog,0,null);
        } catch (Throwable e) {                         // 代码执行进入到catch中，业务方法执行产生异常
            e.printStackTrace();
            LogUtil.afterHandlLog(sysLog,proceed,operLog,1,e.getMessage());
            throw new RuntimeException();
        }finally {
            //调用service中的方法添加到数据库
            operLogService.saveSysOperLog(operLog );
        }

        return proceed ;                                // 返回执行结果
    }
}
